package zack.project.domain.strategy.service.rule.tree.impl;

import zack.project.domain.strategy.adapter.repository.IStrategyRepository;
import zack.project.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import zack.project.domain.strategy.service.rule.tree.ILogicTreeNode;
import zack.project.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;


/**抽奖次数限制的决策树节点,接管用户已抽奖次数大于规定的次数,放行小于规定次数(走RuleLuckAwardLogicTreeNode)
 * @author A1793
 */
@Component("rule_lock")
@Slf4j
public class RuleLockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyRepository repository;
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId,
                                                     Long strategyId,
                                                     Integer awardId,
                                                     String ruleValue,
                                                     Date endDateTime) {
        log.info("规则过滤-次数锁 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);

        long count = 0L;
       try{
            count = Long.parseLong(ruleValue);
       }catch(NumberFormatException e){
           throw new RuntimeException("规则过滤-次数锁异常 ruleValue: " + ruleValue + " 配置不正确");
       }
       Integer userRaffleCount = repository.queryTodayUserRaffleCount(userId,strategyId) ; ;
       //用户抽奖次数大于rule_lock规则节点的rule_value规定的抽奖次数，放行到下一个节点
        //decisionEngine引擎先获取当前treeNode的nodeLine列表，在列表里面根据返回的treeAction的type，
        // 去找相等的nodeLine的rule_limit_value对应to_node的rule_key
       if(userRaffleCount >= count){
           return DefaultTreeFactory.TreeActionEntity.builder()
                   .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                    .build();
       }
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER).
                build();
    }
}
